Crate log_derive

Source
Expand description

§Log Derive

log-derive provides a simple attribute macro that facilitates logs as part of the log facade
Right now it contains two macros logfn, logfn_inputs these macros are only for functions but still have a lot of power.

§Use

The basic use of these macros is by putting one or both of them on top of the function like this: #[logfn(INFO)]

The logfn macro is used to log the output of the function and logfn_inputs is used to log the inputs.
Please notice, the arguments being logged must implement the Debug trait.
(i.e. logfn requires the output to be Debug and logfn_inputs require the inputs to be Debug)

The macros will accept all log levels provided by the log facade.
In logfn if the function returns a Result type the macro will accept the following additional attributes:
(ok = "LEVEL") and (err = "LEVEL") this can provide different log levels if the function failed or not.

By default the macro uses the following formatting to print the message:
logfn: ("FUNCTION_NAME() => {:?}", return_val)
logfn_inputs: "FUNCTION_NAME(a: {:?}, b: {:?})", a, b)
This can be easily changed using the fmt attribute: #[logfn(LEVEL, fmt = "Important Result: {:}")
which will accept format strings similar to println!.

§Examples

use log_derive::{logfn, logfn_inputs};

struct Error;
struct Success;
enum Status { Alive, Dead, Unknown }

#[logfn(Warn)]
#[logfn_inputs(Info, fmt = "Checking if {:?} is alive")]
fn is_alive(person: &Person) -> Status {
   match person.ping() {
       Pong => Status::Alive,
       Timeout => if person.is_awake() {
           Unknown
       } else {
           Dead
       }
  }
}

#[logfn_inputs(Info)]
#[logfn(ok = "TRACE", err = "ERROR")]
fn call_isan(num: &str) -> Result<Success, Error> {
    if num.len() >= 10 && num.len() <= 15 {
        Ok(Success)
    } else {
        Err(Error)
    }
}

#[logfn(INFO, fmt = "a + b = {}")]
#[logfn_inputs(Trace, fmt = "adding a: {:?} and b: {:?}")]
fn addition(a: usize, b: usize) -> usize {
    a + b
}

#[logfn_inputs(Info)]
#[logfn(ok = "TRACE", log_ts = true)]
fn time_this(num: &str) -> Result<Success, Error> {
    if num.len() >= 10 && num.len() <= 15 {
       std::thread::sleep(Duration::from_secs(1));
        Ok(Success)
    } else {
        Err(Error)
    }
}

Attribute Macros§

  • Logs the result of the function it’s above.
  • Logs the inputs of the function